package com.wk.config;

import com.wk.entity.CmfzMenu;
import com.wk.service.CmfzMenuService;
import com.wk.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;

@Configuration
@Slf4j
@Aspect
public class CacheAop {

    @Autowired
    private RedisUtil redisUtil;


    //前置通知,增删改操作之前执行
    @Before("@annotation(com.wk.annotation.DeleteCacheAnnotation)")
    public void deleteCache(JoinPoint joinPoint){
        //key是类名或者对象名,  
        String name = joinPoint.getTarget().getClass().getName();
        log.info("获取到的key"+name);
        redisUtil.del(name);
    }

    //添加缓存,配置成环绕通知

    @Around("@annotation(com.wk.annotation.AddCacheAnnotation)")
    public Object addCache(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;


        //先获取key,通过key拿到结果集
        String key = joinPoint.getTarget().getClass().getName();
        log.info("获取到的key"+key);
        //再获取每个hashkey(方法名)
        String hashKey = joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            hashKey += arg;
        }
        log.debug("hashKey"+hashKey);
        //获取结果集
        result = redisUtil.hget(key,hashKey);
        //如果结果集为空,就从数据库中查
        if(result==null){
            log.info("缓存中没有数据");
            result = joinPoint.proceed();
            HashMap map = new HashMap();
            map.put(hashKey,result);
            //存入redis
            redisUtil.hmset(key,map,60*60*60);
        }else{
            log.debug("缓存中有数据");
        }
        //不为空,直接返回
        return result;
    }
}
